import React, {FC, useEffect, useState} from "react";
import {Form, Input, message, Modal, Popconfirm, Select, Table, Tooltip} from "antd";
import QR from "../../../components/QR";
import {inject, observer} from "_mobx-react@6.3.1@mobx-react";
import api from "../../../api";
import {reg} from "../../../utils";
import BreadcrumbPath from "../../../components/BreadcrumbPath";

const ProjectScore: FC<any> = ({MobxData}) => {
    // 用户列表信息
    const {userList, getUserList} = MobxData;
    // 项目信息
    const {projectList, getProjectList, changeProjectList} = MobxData;
    // 班级列表
    const {classList, getClassList, changeClassList} = MobxData;

    const {userInfo} = MobxData;

    const [url, setUrl] = useState('');
    const [id, setId] = useState('');

    // 表格数据
    const [dataSource, setDataSource] = useState<Array<any>>([]);
    // 对话框是否可见
    const [isModalVisible, setIsModalVisible] = useState(false);

    const [form] = Form.useForm();

    // 弹出框宽度
    const [modalWidth, setModalWidth] = useState("30%");

    // 搜索
    // searchInput, searchSelect
    const [searchInput, setSearchInput] = useState("");
    const [searchSelect, setSearchSelect] = useState("");

    // 表头内容
    const columns = [
        {
            title: '项目名称',
            dataIndex: 'name',
            key: 'name',
            width: 'auto',
        },
        {
            title: '项目类别',
            dataIndex: 'type',
            key: 'type',
            width: 'auto',
        },
        {
            title: '亮点及内容',
            dataIndex: 'content',
            key: 'content',
            width: 'auto',
            ellipsis: {
                showTitle: false,
            },
            render: (introduce: any) => (
                <Tooltip placement="topLeft" title={introduce}
                         overlayInnerStyle={{maxHeight: "200px", overflowY: "auto"}}>
                    {introduce}
                </Tooltip>
            ),
        },
        {
            title: '项目地址',
            dataIndex: 'url',
            key: 'url',
            width: 'auto',
            render: (text: any, record: any) => (
                <QR url={text}><a href={text} target="_blank">{text}</a></QR>
            )
        },
        {
            title: '用户名',
            dataIndex: 'username',
            key: 'username',
            width: 'auto',
        },
        {
            title: '成绩',
            dataIndex: 'score',
            key: 'score',
            width: 'auto',
            render: (text: any, record: any) => text > 0 ? text : "待评分"
        },
        {
            title: '操作',
            key: 'action',
            width: '200px',
            render: (text: any, record: any, index: any) => {
                return (
                    <div style={{color: "#409eff"}}>
                    <span style={{margin: "0 10px", cursor: "pointer"}} onClick={() => {
                        setId(record.key);
                        setUrl(record.url)
                        setIsModalVisible(true);
                    }}>评分</span>
                        <Popconfirm
                            title="确定要删除吗?"
                            onConfirm={() => {
                                // console.log("删除");
                                // 删除项目
                                api.delProject({id: record.key}).then(res => {
                                    message.success(res.msg);
                                }).catch(err => {
                                    message.error(err.msg);
                                })
                                // 更新数据
                                getProjectList();
                            }}
                            okText="确定"
                            cancelText="取消"
                        >
                            <span style={{margin: "0 10px", cursor: "pointer"}}>删除</span>
                        </Popconfirm>
                    </div>
                )
            }
        }
    ];
    // 管理员能看不能操作
    if (userInfo.role === 2) {
        columns.pop();
    }

    useEffect(() => {
        getProjectList();
        getClassList();
        getUserList();
    }, [])
    useEffect(() => {
        // 拼装表格数据
        setDataSource(projectList.map((item: any) => ({
            key: item._id,
            name: item.name,
            type: item.type,
            content: item.content,
            url: item.url,
            username: item.username,
            score: item.score,
            classname: userList.find((user: any) => user.username === item.username)?.classname
        })))
    }, [projectList])

    const handleOk = () => {
        // 验证表单
        form.validateFields().then(values => {
            values.id = id;
            // console.log(values);
            // 更新项目信息
            api.upProject(values).then((res) => {
                message.success(res.msg);
            }).catch(err => {
                message.error(err);
            })

            // 更新数据
            getProjectList()
            // 关闭对话框
            setIsModalVisible(false)
        }).catch(err => {
        })
    }
    const search = () => {
        setDataSource(
            projectList
                .map((item: any) => ({
                    key: item._id,
                    name: item.name,
                    type: item.type,
                    content: item.content,
                    url: item.url,
                    username: item.username,
                    score: item.score,
                    classname: userList.find((user: any) => user.username === item.username)?.classname
                }))
                .filter((item: any) => {
                    if (searchInput != "" && searchSelect != "") {
                        return Object.values(item).some((value: any) => value.toString().includes(searchInput)) && item.classname === searchSelect
                    } else if (searchInput != "") {
                        return Object.values(item).some((value: any) => value.toString().includes(searchInput))
                    } else if (searchSelect != "") {
                        return item.classname === searchSelect
                    }
                    return true
                })
        )
    }
    useEffect(() => {
        search()
    }, [searchInput, searchSelect])

    return (
        <div>
            {/*<h1>我的项目</h1>*/}
            <BreadcrumbPath/>
            <Input type="search" style={{width: "20%"}} placeholder="输入您想要搜索的关键词" onChange={(e) => {
                setSearchInput(e.target.value)
            }}/>
            <Select defaultValue="全部" placeholder="请选择班级" style={{width: "20%"}} onChange={(value) => {
                setSearchSelect(value)
            }}>
                <Select.Option value="" key="all">全部</Select.Option>
                {
                    classList.map((item: any) => {
                        return <Select.Option value={item.name} key={item._id}>{item.name}</Select.Option>
                    })
                }
            </Select>
            <Table dataSource={dataSource} columns={columns} sticky
                   pagination={{
                       pageSize: 8,
                       hideOnSinglePage: true,
                       responsive: true,
                       position: ["bottomCenter"],
                       showQuickJumper: true
                   }}/>
            <Modal title="修改用户信息" okText="提交" cancelText="取消" visible={isModalVisible}
                   width={modalWidth}
                   style={{top: 0}}
                   onOk={handleOk}
                   onCancel={() => {
                       setId("");
                       setUrl("");
                       setIsModalVisible(false)
                       form.resetFields();
                   }}>
                <Select defaultValue="手机端比例" style={{width: "100%"}} onChange={(value) => {
                    setModalWidth(value)
                }}>
                    <Select.Option value="30%">手机端比例</Select.Option>
                    <Select.Option value="90%">电脑端比例</Select.Option>
                </Select>
                <iframe src={url}
                        sandbox="allow-same-origin allow-forms allow-scripts"
                        style={{border: 0}}
                        seamless
                        width="100%" height="550px"
                ></iframe>
                <Form
                    name="basic"
                    form={form}
                    layout='vertical'
                >
                    <Form.Item
                        label="成绩"
                        name="score"
                        rules={[{required: true, message: '项目成绩不能为空'}, {
                            pattern: reg.score,
                            message: '项目成绩必须为数字,不能为负数,且不能超过100'
                        }]}
                    >
                        <Input placeholder="请输入成绩"/>
                    </Form.Item>
                </Form>
            </Modal>
        </div>
    )
}
export default inject('MobxData')(observer(ProjectScore));